import React from 'react';
import { Select } from 'antd';
import './index.scss';

const { Option } = Select;

let timeout;
let currentValue;

function fetch(value, callback) {
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentValue = value;

  let search = () => {
    window.axios.get('/search', {
      params: {
        keywords: value
      }
    })
    .then((response) => {
      if (currentValue === value) {
        const { songs } = response.data.result;
        songs.forEach(s => {
          s._name = s.name + (s.alias&&s.alias.length?'（'+s.alias[0]+'）':'') + ' - ' + s.artists[0].name
        })
        callback(songs);
      }
    })
    .catch((error) => {
      console.log(error);
    });
  }

  timeout = setTimeout(search, 300);
}

function getUrl(id, callback) {
  window.axios.get('/song/url', {
    params: {
      id
    }
  })
  .then((response) => {
    const { url } = response.data.data[0];
    callback(url);
  })
  .catch((error) => {
    console.log(error);
  });
}

class SearchSong extends React.Component {
  state = {
    songs: [],
    value: undefined,
  };

  handleSearch = value => {
    if (value) {
      fetch(value, songs => this.setState({ songs }));
    } else {
      this.setState({ songs: [] });
    }
  };

  handleChange = (id) => {
    id = parseInt(id);
    let song = null;
    this.state.songs.some(s => {
      if (s.id === id) {
        song = s;
        return true
      }
      return false;
    })
    this.setState({ value: song.name });
    if (id && song) {
      getUrl(id, url => this.props.onChange( { url, ...song } ));
    }
  };

  render() {
    const options = this.state.songs.map(s => <Option key={s.id}>{s._name}</Option>);
    return (
      <div className="SearchSong">
        <Select
          showSearch
          value={this.state.value}
          placeholder={this.props.placeholder}
          style={this.props.style}
          defaultActiveFirstOption={false}
          showArrow={false}
          filterOption={false}
          onSearch={this.handleSearch}
          onChange={this.handleChange}
          notFoundContent={null}
          size="large"
        >
          {options}
        </Select>
      </div>
    );
  }
}

export default SearchSong;
